package com.codingvip.LRU;

import com.sun.media.sound.DLSInfo;

import javax.sound.sampled.DataLine;
import java.util.Hashtable;

/**
 * @Author Tony.Han
 * @Created at 2020/4/9 2:46 下午
 * Desc:
 */
public class LRUCache2 {

    private Hashtable<Integer, DLinkedNode> cache = new Hashtable<>();
    private int size;
    private int capacity;
    private DLinkedNode head, tail;


    public LRUCache2(int capacity) {
        this.size = 0;
        this.capacity = capacity;
        head = new DLinkedNode();
        tail = new DLinkedNode();
        head.next = tail;
        tail.prev = head;

    }

    public int get(int key) {
        DLinkedNode node = cache.get(key);
        if (node == null) {
            return -1;
        }
        moveToHead(node);
        return node.value;
    }

    public void put(int key, int value) {
        DLinkedNode node = cache.get(key);
        if (null == node) {
            DLinkedNode newNode=new DLinkedNode(key, value);
            ++size;
            addNode(newNode);
            cache.put(key, newNode);

            if (size > capacity) {
                DLinkedNode tail = popTail();
                cache.remove(tail.key);
                --size;
            }


        }else {
            node.value = value;
            moveToHead(node);
        }



    }

    private void moveToHead(DLinkedNode node) {
        addNode(node);
        removeNode(node);
        size--;
    }


    private void addNode(DLinkedNode node) {
        node.prev = head;
        node.next = head.next;
        head.next.prev = node;
        head.next = node;

    }

    private void removeNode(DLinkedNode node) {

        node.prev.next = node.next;
        node.next.prev = node.prev;

        node.prev = null;
        node.next = null;

    }

    private DLinkedNode popTail() {
        DLinkedNode result = tail.prev;
        removeNode(result);

        return result;
    }

    class DLinkedNode {
        int key;
        int value;
        DLinkedNode prev;
        DLinkedNode next;

        public DLinkedNode(int key, int value) {
            this.key = key;
            this.value = value;
        }

        public DLinkedNode() {
        }
    }


}
